﻿using HttpWebApiTest.Common;
using HttpWebApiTest.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace HttpWebApiTest.Services
{
    /// <summary>
    /// HttpClient使用方式1：直接使用方式。
    /// 这种使用方式适合一次性的 HTTP 请求调用。
    /// 弊端是如果多次都要请求某站点的接口（比如：github），那就得写很多重复代码配置 HttpClient。
    /// </summary>
    public class HttpClientService
    {
        /// <summary>
        /// 注入HttpClientFactory
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public HttpClientService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        IHttpClientFactory _httpClientFactory;

        /// <summary>
        /// 从远API获取用户信息
        /// get http://localhost:5000/api/user/yus/12
        /// </summary>
        /// <returns></returns>
        public string GetInfoRemote()
        {
            var client = _httpClientFactory.CreateClient();

            //配置HttpClien
            ConfigHttpClient(client);

            var url = "/api/user/yus/12";
            //var url = "http://localhost:5000/api/user/yus/12";

            //Get url
            string result = client.GetStringAsync(url).Result;
            return result;
        }

        /// <summary>
        /// 向远程服务器提交数据
        /// post http://localhost:5000/api/setuser
        /// </summary>
        /// <returns></returns>
        public string SetInfoRemote()
        {
            var client = _httpClientFactory.CreateClient();

            //配置HttpClien
            ConfigHttpClient(client);

            var url = "/api/setuser";
            //var url = "http://localhost:5000/api/user/yus/12";

            //构造要提交数据
            var httpContent = new JsonContent(InputMode.Build());
            //或
            //var json = JsonConvert.SerializeObject(InputMode.Build());
            //var httpContent = new StringContent(json, Encoding.UTF8, "application/json");

            //Post Url
            var response = client.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                return response.ToString();
            }

        }


        /// <summary>
        /// 配置HttpClien
        /// </summary>
        /// <param name="client"></param>
        private void ConfigHttpClient(HttpClient client)
        {
            //请求的根地址
            client.BaseAddress = new Uri("http://localhost:5000");

            //设置请求头信息
            //客户端类别
            client.DefaultRequestHeaders.Add(Consts.HeaderUserAgent, "HttpClientFactory-Sample");
            //JWT认证信息
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(Consts.AuthorizationBearer, "jwt token");
            //自定义的 客户端ID
            client.DefaultRequestHeaders.Add(Consts.HeaderAppID, "MyApp");
        }
    }
}
